package com.metal.gear.certification.controller;

import com.metal.gear.certification.entity.dto.permission.DepartPermissionSaveDto;
import com.metal.gear.certification.entity.dto.permission.PermissionSaveAndEditDto;
import com.metal.gear.certification.entity.po.SysPermission;
import com.metal.gear.certification.entity.vo.permission.CurrentUserPermissionVo;
import com.metal.gear.certification.entity.vo.permission.PermissionButtonVo;
import com.metal.gear.certification.entity.vo.permission.PermissionMenuVo;
import com.metal.gear.certification.service.ISysDepartPermissionService;
import com.metal.gear.certification.service.ISysPermissionService;
import com.metal.gear.certification.utils.PermissionDataUtil;
import com.metal.gear.common.constant.CommonConstant;
import com.metal.gear.common.entity.Result;
import com.metal.gear.common.exception.SzlBusinessException;
import com.metal.gear.common.util.oConvertUtils;
import com.metal.gear.common.util.tree.SzlTreeUtil;
import io.swagger.annotations.ApiParam;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜单权限表 前端控制器
 * </p>
 *
 * @Author scott
 * @since 2018-12-21
 */
@Slf4j
@RestController
@RequestMapping("/sys/permission/replace")
@Tag(name  = "2.菜单权限控制器")
public class SysPermissionController {

    @Autowired
    private ISysPermissionService sysPermissionService;


    @Autowired
    private ISysDepartPermissionService sysDepartPermissionService;




    @Operation(summary = "查询系统菜单列表(一级菜单)")
    @GetMapping(value = "/a/listTopMenu",produces = {MediaType.APPLICATION_JSON_VALUE})
    public Result<List<PermissionMenuVo>> listTopMenu() {
        try {
            return Result.ok(
                    sysPermissionService.listTopMenu().stream()
                            .map(PermissionMenuVo::convertFrom)
                            .collect(Collectors.toList())
            );
        } catch (Exception e) {
            throw new SzlBusinessException("查询一级菜单时产生错误", e);
        }
    }

    @Operation(summary ="查询系统菜单列表(子菜单)")
    @GetMapping(value = "/a/listSubMenuAndButton",produces = {MediaType.APPLICATION_JSON_VALUE})
    public Result<List<PermissionMenuVo>> listSubMenu(@RequestParam("parentId") String parentId) {
        try {
            return Result.ok(
                    sysPermissionService.listSubMenu(parentId).stream()
                            .map(PermissionMenuVo::convertFrom)
                            .collect(Collectors.toList())
            );

        } catch (Exception e) {
            throw new SzlBusinessException("查询子菜单和按钮时产生错误", e);
        }
    }


    @Operation(summary ="批量查询子权限")
    @GetMapping(value = "/a/getSystemSubmenuBatch",produces = {MediaType.APPLICATION_JSON_VALUE})
    public Result getSystemSubmenuBatch(@RequestParam("parentIds") @ApiParam("id间以“,”分隔") String parentIds) {
        try {
            List<SysPermission> list = sysPermissionService.listByParentIds(parentIds);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return Result.ok("接口保留还未实现");
    }


    /**
     * 查询当前用户拥有的菜单权限和按钮权限
     *
     * @return
     */
    @RequestMapping(value = "/x/getUserPermissionByToken", method = RequestMethod.GET,produces = {MediaType.APPLICATION_JSON_VALUE})
    @Operation(summary ="当前用户权限")
    public Result<CurrentUserPermissionVo> getUserPermissionByToken() {
        try {
//            CurrentUserPermissionVo.CurrentUserPermissionVoBuilder currentUserPermissionVoBuilder
//                    = CurrentUserPermissionVo.builder();
//            //直接获取当前用户不适用前端token
//            LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//            if (oConvertUtils.isEmpty(loginUser)) {
//                return Result.error("请登录系统！");
//            }
//            //用户权限集合
//            List<SysPermission> metaList = sysPermissionService.queryByUser(loginUser.getUsername());
//
//            List<PermissionMenuVo> permissionMenuVos = generalMenuPermission(metaList);
//            List<PermissionButtonVo> permissionButtonVos = generalButtonPermission(metaList);
//            return Result.ok(
//                    currentUserPermissionVoBuilder
//                            .menu(permissionMenuVos)
//                            .auth(permissionButtonVos)
//                            .build()
//            );
            return Result.ok();
        } catch (Exception e) {
            throw new SzlBusinessException("查询当前用户权限失败", e);
        }
    }

    @Operation(summary ="添加菜单")
    @PostMapping(value = "/a/add",produces = {MediaType.APPLICATION_JSON_VALUE})
    public Result<Boolean> add(@RequestBody PermissionSaveAndEditDto dto) {
        try {
            sysPermissionService.save(PermissionSaveAndEditDto.TranslateTo(dto));
            return Result.ok("添加菜单成功！");
        } catch (Exception e) {
            throw new SzlBusinessException("添加菜单失败", e);
        }
    }


    @Operation(summary ="编辑菜单")
    @PostMapping(value = "/a/edit",produces = {MediaType.APPLICATION_JSON_VALUE})
    public Result<Boolean> edit(@RequestBody PermissionSaveAndEditDto dto) {
        try {
            SysPermission permission = PermissionDataUtil.intelligentProcessData(PermissionSaveAndEditDto.TranslateTo(dto));
            sysPermissionService.editPermission(permission);
            return Result.ok("修改成功！");
        } catch (Exception e) {
            throw new SzlBusinessException("添加菜单失败", e);

        }
    }

    @Operation(summary ="删除菜单")
    @RequestMapping(value = "/a/delete", method = RequestMethod.DELETE,produces = {MediaType.APPLICATION_JSON_VALUE})
    public Result<Boolean> delete(@RequestParam(name = "id") String id) {
        try {
            sysPermissionService.deletePermission(id);
            return Result.ok("删除成功!");
        } catch (Exception e) {
            throw new SzlBusinessException("删除失败", e);
        }
    }


    @Operation(summary ="批量删除菜单")
    @RequestMapping(value = "/a/deleteBatch", method = RequestMethod.DELETE,produces = {MediaType.APPLICATION_JSON_VALUE})
    public Result<Boolean> deleteBatch(@RequestParam(name = "ids") String ids) {
        try {
            String[] arr = ids.split(",");
            for (String id : arr) {
                if (oConvertUtils.isNotEmpty(id)) {
                    sysPermissionService.deletePermission(id);
                }
            }
            return Result.ok("删除成功!");
        } catch (Exception e) {
            throw new SzlBusinessException("删除失败", e);
        }
    }


    @Operation(summary ="检测菜单路径是否存在")
    @RequestMapping(value = "/b/checkPermDuplication", method = RequestMethod.GET,produces = {MediaType.APPLICATION_JSON_VALUE})
    public Result<Boolean> checkPermDuplication(@RequestParam(name = "id", required = false) String id,
                                               @RequestParam(name = "url") String url,
                                               @RequestParam(name = "alwaysShow") Boolean alwaysShow) {
            return Result.ok(sysPermissionService.checkPermDuplication(id, url, alwaysShow));
    }


    @Operation(summary ="获取全部的权限树")
    @GetMapping(value = "/c/queryTreeList",produces = {MediaType.APPLICATION_JSON_VALUE})
    public Result<List<PermissionMenuVo>> queryTreeList() {
        try {
            return Result.ok(
                    SzlTreeUtil.build(
                            sysPermissionService.listAllAvailablePermission().stream()
                                    .map(PermissionMenuVo::convertFrom)
                                    .collect(Collectors.toList())
                    )
            );
        } catch (Exception e) {
            throw new SzlBusinessException("获取全部的权限树失败", e);
        }
    }



    /**
     * 获取按钮列表
     *
     * @param metaList
     */
    private List<PermissionButtonVo> generalButtonPermission(List<SysPermission> metaList) {
        return metaList.stream()
                .filter((metaPermission) ->
                        CommonConstant.MENU_TYPE_2.equals(metaPermission.getMenuType())
                                && CommonConstant.STATUS_1.equals(metaPermission.getStatus()))
                .map(PermissionButtonVo::convertFrom)
                .collect(Collectors.toList());
    }


    /**
     * 获取菜单列表
     *
     * @param metaList
     * @return
     */
    private List<PermissionMenuVo> generalMenuPermission(List<SysPermission> metaList) {
        //过滤按钮权限，获取菜单权限
        final List<PermissionMenuVo> collect = metaList.stream()
                .filter((meta) -> !meta.getMenuType().equals(CommonConstant.MENU_TYPE_2))
                .map(PermissionMenuVo::convertFrom)
                .collect(Collectors.toList());
        return SzlTreeUtil.build(collect);
    }


    @Operation(summary ="部门权限Id列表")
    @RequestMapping(value = "/e/queryDepartPermission", method = RequestMethod.GET,produces = {MediaType.APPLICATION_JSON_VALUE})
    public Result<List<String>> queryDepartPermission(@RequestParam(name = "departId") String departId) {
        try {
            return Result.ok(sysDepartPermissionService.listIdByDepartId(departId));
        } catch (Exception e) {
            throw new SzlBusinessException("查询失败", e);
        }
    }


    @Operation(summary ="保存部门授权")
    @RequestMapping(value = "/saveDepartPermission", method = RequestMethod.POST ,produces = {MediaType.APPLICATION_JSON_VALUE})
    public Result<Boolean> saveDepartPermission(@RequestBody DepartPermissionSaveDto departPermissionSaveDto) {
        try {
            String departId = departPermissionSaveDto.getDepartId();
            List<String> permissionIdList = departPermissionSaveDto.getPermissionIdList();
            sysDepartPermissionService.saveDepartPermission(departId, permissionIdList);
            return Result.ok("保存部门授权成功！");
        } catch (Exception e) {
            throw new SzlBusinessException("保存部门授权失败", e);
        }
    }

}
